<template>
  <div class="chart-list">
    <chart-comp
      v-for="(item, index) in chartList"
      :type="item.type"
      :key="index"
      :data="data"
      :list="list"
      :commonData="commonData"
      :geoData="geoData"></chart-comp>
  </div>
</template>

<script>
  // import ChartComp from './chart.vue'
  const ChartComp = () => import(/* webpackChunkName: "chunk-chart" */ './chart.vue');

  export default {
    name: 'ChartList',
    props: {
      chartList: {
        type: Array
      },
      data: {
        type: Object
      },
      list: {
        type: Object
      }
    },
    components: {
      ChartComp
    },
    data() {
      return {
        dataList: [],
        commonData: {
          legendData: [],
          axisData: [],
          seriesData: [],
          allSeriesData: [],
          geoData: {}
        }
      };
    },
    watch: {
      list: {
        handler(v) {
          const pageSize = this.data?.pageSize || v.length;
          this.dataList = v?.data?.slice(0, pageSize) || [];
          if (this.chartList.filter((item) => item.type === '8').length) {
            // 加载地图数据，数据来源https://datav.aliyun.com/portal/school/atlas/area_selector
            import(/* webpackChunkName: "chunk-geo" */ './geo.json').then((geoData) => {
              this.commonData.geoData = geoData;
              this.formatData();
            });
          } else {
            this.formatData();
          }
        },
        deep: true,
        immediate: true
      }
    },
    computed: {
      // 统计项字段
      statsFields() {
        return this.data?.formCondMap?.statsFields || [];
      },
      // 是否有列表头
      hasColHeader() {
        return this.data?.formCondMap?.colHeaders;
      },
      // 分组统计字段数据
      colData() {
        return this.list?.coldata || [];
      },
      rowHeaderKeys() {
        const rowHeaders = this.data?.formCondMap?.rowHeaders || [];
        const keyList = rowHeaders.map((item) => item.aliasTableName + '_' + item.name);
        return keyList;
      }
    },
    methods: {
      // 数据格式化
      formatData() {
        if (!this.list?.data?.length) return;
        this.commonData = {
          ...this.commonData,
          legendData: this.createLegend(),
          axisData: this.createAxis(),
          seriesData: this.createSeries()
        };
        if (
          this.chartList.filter(
            (item) => item.type === '5' || item.type === '6' || item.type === '9'
          ).length
        ) {
          this.commonData.allSeriesData = this.createAllSeriesData();
        }
        console.log('format data', this.commonData);
      },
      // 生成图例数据
      createLegend() {
        return this.statsFields.map((item) => item.aliasDisplay);
      },
      // 生成图表轴线数据
      createAxis() {
        let xAxis = [];
        let yAxis = [];

        xAxis = this.dataList.map((item) => {
          let res = '';
          this.rowHeaderKeys.forEach((key, index) => {
            res = res + (index ? '/' : '') + (item[key][0] || '');
          });
          return res;
        });

        return {
          xAxis,
          yAxis
        };
      },
      // 生成图表数据（列表头维度数据）
      createSeries() {
        const colHeaders = this.data?.formCondMap?.colHeaders;
        let list = [];

        if (colHeaders) {
          // 有列表头
          this.colData.forEach((_, index) => {
            let arr = [];
            this.statsFields.forEach((field, j) => {
              const key = `col_${index}_${field.aliasTableName}_${field.name}`;
              const colDataItem = this.dataList.map((item) => {
                const value = parseFloat(
                  parseFloat((item[key] && item[key][1]) || 0).toFixed(field.digitNum || 0)
                );
                return {
                  v: value,
                  style: (item[key] && item[key][2]) || ''
                };
              });
              arr.push(colDataItem);
            });
            list.push(arr);
          });
        } else {
          this.statsFields.forEach((field, j) => {
            const key = `${field.aliasTableName}_${field.name}`;
            const colDataItem = this.dataList.map((item) => {
              const value = parseFloat(
                parseFloat((item[key] && item[key][1]) || 0).toFixed(field.digitNum || 0)
              );
              return {
                v: value,
                style: (item[key] && item[key][2]) || ''
              };
            });
            list.push(colDataItem);
          });
        }

        return list;
      },
      // 全量数据构造（列表头维度+统计项数据）
      createAllSeriesData() {
        const colHeaders = this.data?.formCondMap?.colHeaders;
        let list = [];

        let dataList = this.list?.data || [];
        dataList.forEach((item, index) => {
          let str = '';
          this.rowHeaderKeys.forEach((key, index) => {
            str = str + (index ? '/' : '') + ((item[key] && item[key][0]) || '');
          });
          list[index] = {
            itemName: str,
            rowIndex: index
          };

          if (colHeaders) {
            // 有列表头
            this.colData.forEach((_, i) => {
              this.statsFields.forEach((field, j) => {
                const key = `col_${i}_${field.aliasTableName}_${field.name}`;
                const value = parseFloat(
                  parseFloat((item[key] && item[key][1]) || 0).toFixed(field.digitNum || 0)
                );
                var mapKey = i + '_' + j;
                list[index][mapKey] = {
                  v: value,
                  style: (item[key] && item[key][2]) || ''
                };
              });
            });
          } else {
            this.statsFields.forEach((field, j) => {
              const key = `${field.aliasTableName}_${field.name}`;
              const value = parseFloat(
                parseFloat((item[key] && item[key][1]) || 0).toFixed(field.digitNum || 0)
              );
              list[index][j] = {
                v: value,
                style: (item[key] && item[key][2]) || ''
              };
            });
          }
        });

        return list;
      }
    }
  };
</script>
